﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Project.MVC.Model;
namespace Project.MVC.MsSQLDAL
{
    public class ImageRepository : IImageRepository
    {
        LinqProjectDataContext dataContext;
        public ImageRepository()
        {
            dataContext = new LinqProjectDataContext();
        }

        public IQueryable<ImageInfo> GetList()
        {
            return dataContext.Images.Select(record => new ImageInfo
                {
                    Id = record.Id,
                    ProductId=record.ProductId,
                    Url=record.Url,
                    IsDefault=record.IsDefault
                });
        }

        public bool Insert(ImageInfo value)
        {
            if (value == null)
                return false;
            try
            {
                var info = General.GetInfo(value);
                dataContext.Images.InsertOnSubmit(info);
                dataContext.SubmitChanges();
                value.Id = info.Id;
                return true;
            }
            catch (Exception)
            {
                throw;
            }
        }

        public bool Update(ImageInfo value)
        {
            if (value == null)
                return false;
            try
            {
                //var info = GetById(value.Id);
                var info = dataContext.Images.Where(c => c.Id == value.Id).SingleOrDefault();
                if (info != null)
                {
                    info.Url=value.Url;
                    info.IsDefault = value.IsDefault;
                    return true;
                }
                return false;
            }
            catch (Exception)
            {
                throw;
            }
        }

        public bool Delete(ImageInfo value)
        {
            if (value == null)
                return false;
            try
            {
                //var info = GetById(value.Id);
                var info = dataContext.Images.Where(c => c.Id == value.Id).SingleOrDefault();
                if (info != null)
                {
                    dataContext.Images.DeleteOnSubmit(info);
                    return true;
                }

                return false;
            }
            catch (Exception)
            {
                throw;
            }
        }

        public int Count()
        {
            return dataContext.Images.Count();
        }

        public void Commit()
        {
            dataContext.SubmitChanges();
        }
    }
}
